package com.dongdongshop.shiro;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration//声明当前是配置类
public class ShiroConfig {
    //将shiro的过滤器链放到spring容器中
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager) {
        //创建过滤器链工厂类
        ShiroFilterFactoryBean factoryBean =new ShiroFilterFactoryBean();
        //添加shiro 内置的过滤器
        /*
        *常用的过滤器
        * anon : 不需要登录就可以访问
        * authc : 必须登陆陆才能访问
        * perms : 登录之后必须有权限才能访
        * role : 登录之后要有权限才能访问
        * logout : 退出登录过滤器
        * .....
        * */
        Map<String,String> filterMap =  new LinkedHashMap<>();//因为LinkedHashMap是存取有序的
        //key 使我们的url ,value 就是我们设置的url做对应的过滤器
        filterMap.put("/index","anon");//不用登录就可以访问
        filterMap.put("/login","anon");//不用登录就可以访问
//        factoryBean.setLoginUrl("/toLogin");
//        factoryBean.setUnauthorizedUrl("/unauthorized");
        //设置安全管理器 DI
        factoryBean.setSecurityManager(defaultWebSecurityManager);
        factoryBean.setFilterChainDefinitionMap(filterMap);

        return factoryBean;
    }
    @Bean
    //将安全管理器放入spring容器中
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();
            securityManager.setRealm(loginRealm);
        return securityManager;
    }
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm loginRealm = new LoginRealm();
        //将加密方式关联我们自定义的realm类
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginRealm;
    }
    @Bean
    //设置密码加密
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
            HashedCredentialsMatcher matcher =new HashedCredentialsMatcher();
            //指定加密的方式
            matcher.setHashAlgorithmName("MD5");
            //设置加密的次数
        matcher.setHashIterations(3);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }
 }
